package com.ruoyi.bole.controller;

import com.ruoyi.anno.Log;
import com.ruoyi.bole.service.EmailService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController()
@RequestMapping("/bole")
public class BoleLoginController {
    @Autowired
    private ISysUserService iuserService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private EmailService  emailService;
    @Log(name = "登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        System.out.println(loginBody.toString());
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest())

        ajax.put(Constants.TOKEN, token);
        ajax.put("user", iuserService.selectUserByUserName(loginBody.getUsername()));
        return ajax;
    }

    //发送找回验证码 根据邮箱和账号
    @PostMapping("/sendCode")
    public AjaxResult sendCode(String userName,String email)
    {
        //先检验该用户是否存在
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setEmail(email);
        if (iuserService.selectUserByEmailAndUserName(sysUser)==null){
            return AjaxResult.error("请检查用户名或邮箱");
        }
        try {
            //先从redis查询今日剩余可用查询次数
            Integer count = redisCache.getCacheObject("Find:findPasswordCount");
            if (count<=0){
                return AjaxResult.error("今日找回次数已用完，可联系客服找回");
            }
            count--;
            redisCache.setCacheObject("Find:findPasswordCount",count);
            //通过邮箱发送校验码 先存入redis 过期时间5分钟
            //生成一个随机验证码
            Random random = new Random();
            Integer code = random.nextInt(999999);
            //存入redis  用TimeUtil
            redisCache.setCacheObject("Find:findPasswordCode:"+email,code,5,TimeUnit.MINUTES);
            emailService.sendSimpleMail(email,"找回密码验证码","你的验证码为："+code+"，有效期5分钟，请勿泄露");
            return AjaxResult.success("发送成功");
        }catch (Exception e){
            System.out.println(e);
            return AjaxResult.error("发送失败，请稍后重试");
        }
    }
    //修改密码
    @PostMapping("/resetPassword")
    public AjaxResult resetPassword(String email,Integer code,String password,String userName)
    {
        //先检验该用户是否存在
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setEmail(email);
        sysUser = iuserService.selectUserByEmailAndUserName(sysUser);
        if (sysUser==null){
            return AjaxResult.error("请检查用户名或邮箱");
        }
//        System.out.println(redisCache.getCacheObject("Find:findPasswordCode:"+email);
        Integer cachedCode = (Integer) redisCache.getCacheObject("Find:findPasswordCode:" + email);
        System.out.println(cachedCode);

        if (cachedCode != null && code.equals(cachedCode)) {
            SysUser sysUserNew = new SysUser();
            sysUserNew.setUserId(sysUser.getUserId());
            sysUserNew.setPassword(SecurityUtils.encryptPassword(password));
            iuserService.updateUser(sysUserNew);
            return AjaxResult.success("修改成功");
        }else{
            return AjaxResult.error("验证码错误");
        }
    }


}
